package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.OrderDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    //查询所有地址信息
    public List<Address> findAll() {
        return addressDao.findAll();
    }

    @Override
    //分页查询地址信息
    public PageResult findPage(QueryPageBean queryPageBean) {

        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();

        PageHelper.startPage(currentPage, pageSize);

        Page<Address> checkGroups = addressDao.findByCondition(queryString);


        return new PageResult(checkGroups.getTotal(), checkGroups.getResult());
    }

    @Override
    //新增地址信息
    public void add(Address address) {
        addressDao.add(address);
    }

    @Override
    //删除地址信息
    public Result del(int id) {
        Integer count = orderDao.findOrderCountById(id);
        if (count != null && count > 0) {
            return new Result(false, MessageConstant.DELETE_ADDRESS_FAIL_REFERENCES);
        } else {
            addressDao.del(id);
            return new Result(true, MessageConstant.DELETE_ADDRESS_SUCCESS);
        }
    }

    @Override
    //查询所有地址名和id
    public List<Map<String, Integer>> findList() {
        return addressDao.findList();
    }
}
